package com.zsh.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.SecretKey;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by zsh on 2023/3/6
 *
 * @author zsh
 */
@Slf4j
public class JwtTokenUtils {
    /**
     * 请求头
     */
    public static final String TOKEN_HEADER = "Authorization";

    /**
     * TOKEN 前缀
     */
    public static final String TOKEN_PREFIX = "Bearer";

    /**
     * 私钥
     */
    private static final String TOKEN_SECRET = "secret";

    /**
     * 令牌过期时间 : one day
     * 测试：改为7天
     */
    private static final long TOKEN_EXPIRATION = 1000 * 60 * 60 * 24 * 5;

    /**
     * 刷新令牌过期时间
     */
    private static final long REFRESH_TOKEN_EXPIRATION = 7 * 24 * 60 * 60 * 1000L;
//    private static final long REFRESH_TOKEN_EXPIRATION = 3 * 60 * 1000L;

    /**
     * 用户id定义
     */
    public static final String USER_ID = "userId";

    /**
     * 密码名定义
     */
    public static final String USERNAME = "username";

    /**
     * 时间戳定义
     */
    public static final String TIMESTAMP = "timestamp";

    public static final String TOKEN_EXP = "tokenExp";
    /**
     * 生成token主题
     */
    public static AuthToken generateAuthToken(String userId, String username) {
        AuthToken authToken = new AuthToken();
        // 1.生成access_token
        String accessToken = generateAccessToken(userId, username);
        String refreshToken = generateRefreshToken(userId, username);
        authToken.setUserId(userId);
        authToken.setUsername(username);
        authToken.setAccessToken(accessToken);
        authToken.setRefreshToken(refreshToken);
        authToken.setTokenExp(TOKEN_EXPIRATION);
        authToken.setRefreshTokenExp(REFRESH_TOKEN_EXPIRATION);
        return authToken;
    }

    /**
     * 根据负责生成JWT的token
     */
    private static String generateToken(Map<String, Object> claims, Long exp) {
        String token = Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate(exp))
                .signWith(SignatureAlgorithm.HS512, TOKEN_SECRET)
                .compact();
        return TOKEN_PREFIX + " " + token;
    }

    /**
     * refreshToken生成
     * @param userId 用户id
     * @param username 用户名
     * @return accessToken
     */
    private static String generateRefreshToken(String userId, String username) {
        // 创建 JWT 刷新令牌
        Map<String, Object> map = new HashMap<>();
        map.put(USER_ID, userId);
        map.put(USERNAME, username);
        return generateToken(map, REFRESH_TOKEN_EXPIRATION);
    }

    /**
     * accessToken生成
     * @param userId 用户id
     * @param username 用户名
     * @return accessToken
     */
    private static String generateAccessToken(String userId, String username) {
        Map<String, Object> map = new HashMap<>();
        map.put(USER_ID, userId);
        map.put(USERNAME, username);
        // 获取当前时间的时间戳
//        long timeStamp = System.currentTimeMillis() / 1000;
//        map.put(TIMESTAMP, timeStamp);
//        map.put(TOKEN_EXP, TOKEN_EXPIRATION / 1000);
        return generateToken(map, TOKEN_EXPIRATION);
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(TOKEN_SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private static Date generateExpirationDate(long expiration) {
        return new Date(System.currentTimeMillis() + expiration);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 解析令牌
     */
    public static Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(TOKEN_SECRET).parseClaimsJws(token).getBody();
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

}




